#include"../include/func.h"

void userLogin(int clientfd){
    char username[32] = {0};
    char* passwd;
    char salt[32] = {0};
    char ciphertext[128] = {0};
    while(1){
        //输入用户名
        memset(username, 0, sizeof(username));
        printf("username:");
        scanf("%s", username);
        //将用户名传给服务器
        train_t train;
        memset(&train, 0, sizeof(train));
        train.length = strlen(username);
        strcpy(train.buff, username);
        send(clientfd, &train, 4+train.length, MSG_WAITALL);
        //接收服务器返回的盐值
        int buflen = 0;
        char buf[128] = {0};
        recv(clientfd, &buflen, 4, MSG_WAITALL);
        recv(clientfd, buf, buflen, MSG_WAITALL);
        if(buf[0]!='$'){
            //服务器未查询到相应用户，返回错误信息
            printf("input right username!\n");
            continue;
        }
        else{
            //输入密码
            passwd = getpass("password:");
            //取得盐值，将密码加密得到密文
            strcpy(salt, buf);
            strcpy(ciphertext, crypt(passwd, salt));
            //将加密后的信息返回给服务器服务器发回判断结果
            memset(&train, 0, sizeof(train));
            train.length = strlen(ciphertext);
            strcpy(train.buff, ciphertext);
            send(clientfd, &train, 4+train.length, MSG_WAITALL);
            //接收服务器返回的验证信息
            memset(&buf, 0, sizeof(buf));
            recv(clientfd, &buflen, 4, MSG_WAITALL);
            recv(clientfd, buf, buflen, MSG_WAITALL);
            if(buf[0] == 'y'){
                printf("Dear %s, Welcome\n", username);
                return;
            }
            else{
                printf("wrong password\n");
                continue;
            }
        }

    }
}
